package com.lujianfei.powersearch.widget

import android.app.TimePickerDialog
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.widget.AppCompatEditText
import java.util.Calendar
import java.util.Locale

class TimePickerEditText @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatEditText(context, attrs) {

    var shouldBlock:(()->Boolean) ?= null

    var onTimeReceive:((timeStr:String, timeStamp:Long)->Unit) ?= null

    init {
        setOnTouchListener(object :OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                if (shouldBlock?.invoke() == true) {
                    return false
                }
                if (event?.action == MotionEvent.ACTION_DOWN) {
                    transferToHourMinute { hourOfDay:Int, minute:Int->
                        showDatePickerDialog(hourOfDay_in = hourOfDay, minute_in = minute)
                    }
                    return true
                }
                return false
            }
        })
        setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                if (shouldBlock?.invoke() == true) {
                    return@setOnFocusChangeListener
                }
                transferToHourMinute { hourOfDay:Int, minute:Int->
                    showDatePickerDialog(hourOfDay_in = hourOfDay, minute_in = minute)
                }
            }
        }
    }

    private fun transferToHourMinute(callback:(hourOfDay:Int, minute:Int)->Unit) {
        val dateStr = text.toString()
        val calendar = Calendar.getInstance()
        if (dateStr.isBlank()) {
            callback.invoke(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE))
        } else {
            val hour = dateStr.split(":")[0]
            val minute = dateStr.split(":")[1]
            callback.invoke(hour.toInt(), minute.toInt())
        }
    }

    private fun showDatePickerDialog(hourOfDay_in:Int, minute_in:Int) {
        val datePicker = TimePickerDialog(context, { view, hourOfDay, minute ->
            val timeStr = String.format(Locale.getDefault(),"%02d:%02d", hourOfDay, minute)
            val timeStamp = hourOfDay * 60 * 60 + minute * 60
            onTimeReceive?.invoke(timeStr, timeStamp.toLong())
        }, hourOfDay_in, minute_in, true)
        datePicker.show()
    }
}